﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using Microsoft.Extensions.DependencyInjection.Extensions;
using WpfSnqkGasAnalysis.Common;
using WpfSnqkGasAnalysis.Model;
using System.IO;
using WpfSnqkGasAnalysis.IBusiness_impl;
using WpfSnqkGasAnalysis.IData;
using WpfSnqkGasAnalysis.IData_impl;

namespace WpfSnqkGasAnalysis
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {

        public App()
        {
            //异常捕获
            this.DispatcherUnhandledException += App_DispatcherUnhandledException;
            //AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;


            //检查数据库是否复制了？1=已经复制，项不在或0表示未复制
            string haveDb = MyConfigReader.GetConfigValue("copyDbDo");
            string run_db_path = MyConfigReader.GetConfigValue("run_db_path");
            if (string.IsNullOrWhiteSpace(haveDb) || haveDb == "0"
              || !File.Exists(run_db_path)
             )
            {
                try
                {
                    //系统运行数据库复制到运行目录中               
                    string dir = Path.GetDirectoryName(run_db_path);
                    if (!System.IO.Directory.Exists(dir))
                    {
                        System.IO.Directory.CreateDirectory(dir);
                    }
                    string sourceDbPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "DataBase", "snqk_sys_analysis.db");
                    if (!File.Exists(sourceDbPath))
                    {
                        ShowAlertHelpter.ShowAlert("出错，程序中没找到数据库文件" + Path.GetFileName(sourceDbPath));
                        return;
                    }
                    if (!File.Exists(run_db_path))
                    {
                        File.Copy(sourceDbPath, run_db_path);
                    }

                    //配置文件记录，标记已经处理
                    string configFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "sysData.ini");
                    string[] arr = File.ReadAllLines(configFile);
                    string oldKV_line = "";
                    foreach (var item in arr)
                    {
                        if (item.Trim().StartsWith("copyDbDo"))
                        {
                            oldKV_line = item;
                            break;
                        }
                    }
                    if (!string.IsNullOrWhiteSpace(oldKV_line))
                    {
                        string all_txt = File.ReadAllText(configFile);
                        all_txt = all_txt.Replace(oldKV_line, "");
                        File.WriteAllText(configFile, all_txt);
                    }
                    File.AppendAllText(configFile, System.Environment.NewLine + "copyDbDo    1");
                }
                catch (Exception ex)
                {
                    var ex1 = ex.InnerException ?? ex;
                    ShowAlertHelpter.ShowAlert("出错，运行db复制异常，" + ex1.Message + "。");
                    return;
                }
            }

            //初始化依赖注入
            var initInterface = ServicesHelpter.serviceProvider;

            //更新数据库的sql
            //Startup += App_Startup;
            UpdateAPP_Sql();
        }

        /// <summary>
        /// 更新数据库字段，表
        /// </summary>
        /// 创建时间：2023-1-17 11:45:01。
        public void UpdateAPP_Sql()
        {
            //string filePath1 = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "AppUpdate1.txt");
            ////判断是否已经执行了
            //if (!File.Exists(filePath1)
            //    || (System.IO.File.ReadAllText(filePath1) == null
            //    || !System.IO.File.ReadAllText(filePath1).Equals("1"))
            // )
            //{
            //    try
            //    {
            //        SourceDictBusiness sourceDictBusiness = new SourceDictBusiness();
            //        var list = sourceDictBusiness.GetAll();
            //        int index = 9999;
            //        foreach (var item in list)
            //        {
            //            var dal2 = new BaseDAL();
            //            string sql = $" update   source_dict   set   d_sort ={index}   where  id={item.Id}; ";
            //            int count = dal2.ExecSqlCmd(sql, null, c =>
            //            {
            //                return c.ExecuteNonQuery();
            //            });
            //            if (count > 0)
            //            {
            //                index++;
            //                LogHelpter.AddLog("版本更新，" + sql + " 执行成功");
            //            }
            //        }
            //        System.IO.File.WriteAllText(filePath1, "1");
            //    }
            //    catch (Exception ex)
            //    {
            //        LogHelpter.AddLog("版本更新异常，" + ex.Message);
            //    }
            //}
        }


        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
        }

        private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            e.Handled = true;
            var ex2 = e.Exception.InnerException ?? e.Exception;
            LogHelpter.AddLog(ex2.ToString(), null, "APP_Exception");
            ShowAlertHelpter.ShowAlert(ex2.Message);
            //throw new NotImplementedException();
        }
    }
}
